#coding:utf-8
from lovewith.subscribe.models import Subscribe


class SubscribeApi:
    def __init__(self):
        pass

    #校验是否订阅过
    @staticmethod
    def check_data(keyword=None, user_id=None):
        if keyword and user_id:
            image_data = Subscribe.objects.filter(keyword=keyword, user_id=user_id)
            if image_data.exists():
                return image_data[0]
        return None

    #获取用户订阅的关键词
    @staticmethod
    def get_by_uid(user_id):
        keywords = []
        sub_filter_data = Subscribe.objects.filter(user_id=user_id).order_by('-id')
        for data in sub_filter_data:
            keywords.append({
                'cate_id': data.cate_id,
                'keyword': data.keyword
            })
        return keywords

    #增加订阅
    def add(self, keyword, cate, user):
        is_exist = self.check_data(keyword=keyword, user_id=user.id)
        if not is_exist:
            new_subscribe = Subscribe(
                keyword=keyword,
                cate=cate,
                user=user
            )
            new_subscribe.save()
            return True
        return False

    #删除订阅
    def delete(self, keyword, user):
        sub_data = self.check_data(keyword=keyword, user_id=user.id)
        if sub_data:
            sub_data.delete()
        return True

